<template>
  <div class="user_list">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <div class="input_box">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-input clearable @clear="getTableList" placeholder="请输入搜索内容" v-model="query_data.query" class="input-with-select">
                <el-button @click="getTableList" slot="append" icon="el-icon-search"></el-button>
              </el-input>
            </el-col>
            <el-col :span="4">
              <el-button @click="AddDialogVisible = true" type="primary">添加用户</el-button>
            </el-col>
          </el-row>
        </div>

        <!-- 添加用户的弹窗 -->
        <el-dialog
          title="添加用户"
          :visible.sync="AddDialogVisible"
          width="50%"
          @close="AddDialogClose"
          >
          <el-form :rules="AddUserRules" ref="AddForm" :model="AddUserForm" label-width="80px">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="AddUserForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input v-model="AddUserForm.password"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="AddUserForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="AddUserForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="AddDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmAddUser">确 定</el-button>
          </span>
        </el-dialog>
        
        <!-- 编辑用户的弹窗 -->
        <el-dialog
          title="编辑用户"
          :visible.sync="editDialogVisible"
          width="50%"
          @close="editDialogClose"
          >
          <el-form :rules="editUserRules" ref="editForm" :model="editUserForm" label-width="80px">
            <el-form-item label="用户名" prop="username">
              <el-input disabled v-model="editUserForm.username"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="editUserForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机" prop="mobile">
              <el-input v-model="editUserForm.mobile"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmeditUser">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 设置用户角色的弹框 -->
        <el-dialog
          title="分配角色"
          :visible.sync="settingRolesDialogVisible"
          @close="currentRoleID=''"
          width="50%"
          class="current_roles_info"
        >
        <div><span>当前的用户:</span>{{currentRoleInfo.username}}</div>
        <div><span>当前的角色:</span>{{currentRoleInfo.role_name}}</div>
        <div class="select_box">
          <span>分配新角色:</span>
          <el-select v-model="currentRoleID" placeholder="请选择">
            <el-option
              v-for="item in role_list"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </div>
        
          <span slot="footer" class="dialog-footer">
            <el-button @click="settingRolesDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="confirmSettingRoles">确 定</el-button>
          </span>
        </el-dialog>

        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%">
          <el-table-column align='center' type="index" label="#"></el-table-column>
          <el-table-column align='center' prop="username" label="姓名"></el-table-column>
          <el-table-column align='center' prop="email" label="邮箱"></el-table-column>
          <el-table-column align='center' prop="mobile" label="电话"></el-table-column>
          <el-table-column align='center' prop="role_name" label="角色"></el-table-column>
          <el-table-column align='center' label="状态">
            <template slot-scope="scope">
              <el-switch @change="SwitchChange(scope.row)" :disabled="scope.row.username=='admin'?true:false" v-model="scope.row.mg_state"></el-switch>
            </template>
          </el-table-column>
          <el-table-column align='center' label="操作" width="220">
            <template slot-scope="scope">
              <el-button :disabled="scope.row.username=='admin'?true:false" @click="showEditDialog(scope.row.id)" size="mini" type="primary" icon="el-icon-edit"></el-button>
              <el-button :disabled="scope.row.username=='admin'?true:false" @click="showDelDailog(scope.row.id)" size="mini" type="danger" icon="el-icon-delete"></el-button>
              <el-tooltip :enterable='false'  class="item" effect="dark" content="分配角色" placement="top">
                <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSettingRolesDailog(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="query_data.pagenum"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="query_data.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default{
  data(){
    var emailValidate = (rules,val,cb) =>{
      const checkEmail = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
      if( checkEmail.test(val)){
        return cb()
      }
      cb(new Error('请输入正确的邮箱格式'))
    }

    var mobileValidate = (rules,val,cb) =>{
      const checkMobile=/^((0[0-9]{2,3}\-)?([2-9][0-9]{6,7})+(\-[0-9]{1,4})?)$|^(0?[1][3578][0-9]{9})$|^(400[0-9]{7})$/
      if(checkMobile.test(val)){
        return cb()
      }
      cb(new Error('请输入正确的手机号码格式'))
    }

    return {
      query_data:{
        query:'',
        pagenum:1,
        pagesize:5
      },
      tableData:[],
      total:0,
      AddDialogVisible:false,
      AddUserForm:{
        username:'',
        password:'',
        email:'',
        mobile:''
      },
      AddUserRules:{
        username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator: emailValidate, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator: mobileValidate, trigger: 'blur' }
          ],
      },
      editUserForm:{},
      editDialogVisible:false,
      editUserRules:{
        username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur' }
          ],
          email: [
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator: emailValidate, trigger: 'blur' }
          ],
          mobile: [
            { required: true, message: '请输入手机号', trigger: 'blur' },
            { validator: mobileValidate, trigger: 'blur' }
          ],
      },
      settingRolesDialogVisible:false,
      currentRoleInfo:{},
      role_list:[],
      currentRoleID:''
    }
  },
  created(){
    this.getTableList()
  },
  methods:{
    async getTableList(){
      const res = await this.$http.get('users',{params:this.query_data})
      // console.log(res);
      if(res.data.meta.status!==200) return this.$message(res.data.meta.msg)
      this.total=res.data.data.total
      this.tableData=res.data.data.users
    },
    async SwitchChange(row){
      const res= await this.$http.put(`users/${row.id}/state/${row.mg_state}`)
      console.log(res);
      if(res.data.meta.status!==200) return this.$message.error(res.data.meta.msg)
      this.$message.success(res.data.meta.msg)
    },
    AddDialogClose(){
      this.$refs.AddForm.resetFields()
    },
    confirmAddUser(){
      this.$refs.AddForm.validate(async valid=>{
        // console.log(valid);
        if(!valid) return
        const res =await this.$http.post('users',this.AddUserForm)
        // console.log(res);
        if(res.data.meta.status!==201) return this.$message.error(res.data.meta.msg)
        this.AddDialogVisible=false
        this.$message.success(res.data.meta.msg)
        this.getTableList()
      })
    },
    async showEditDialog(id){
      this.editDialogVisible=true
      const res=await this.$http.get(`users/${id}`)
      console.log(res);
      if(res.data.meta.status!==200) return this.$message.error(res.data.meta.msg)
      this.editUserForm=res.data.data
    },
    editDialogClose(){
      this.$refs.editForm.resetFields()
    },
    confirmeditUser(){
      this.$refs.editForm.validate(async valid=>{
        if(!valid) return 
        const res= await this.$http.put(`users/${this.editUserForm.id}`,{email:this.editUserForm.email,mobile:this.editUserForm.mobile})
        console.log(res);
        if(res.data.meta.status!==200) return this.$message.error(res.data.meta.msg)
        this.editDialogVisible=false
        this.$message.success(res.data.meta.msg)
        this.getTableList()

      })

    },
    async showDelDailog(id){
      const res= await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(error=>{
          return error
        })
        console.log(res);
        if(res==="confirm"){
          const res=await this.$http.delete(`users/${id}`)
          console.log(res);
          if(res.data.meta.status!==200) return this.$message.error(res.data.meta.msg)
          this.$message.success(res.data.meta.msg)
          this.getTableList()
        }
    },
    showSettingRolesDailog(row){
      console.log(row);
      this.currentRoleInfo=row
      this.getRoleList()
      this.settingRolesDialogVisible=true

    },
    async getRoleList(){
      const res=await this.$http.get('roles')
      this.role_list=res.data.data
    },
    async confirmSettingRoles(){
      // console.log(this.currentRoleID);
      const res=await this.$http.put(`users/${this.currentRoleInfo.id}/role`,{rid:this.currentRoleID})
      console.log(res);
      if(res.data.meta.status!==200) return this.$message.error('设置失败')
      this.$message.success('设置成功')
      this.settingRolesDialogVisible=false
      this.getTableList()
    },
    handleSizeChange(newSize){
      // console.log(newSize);
      this.query_data.pagesize=newSize
      this.getTableList()
    },
    handleCurrentChange(currentPage){
      // console.log(currentPage);
      this.query_data.pagenum=currentPage
      this.getTableList()
    }
  }
}
</script>

<style lang="less" scoped>
.user_list{
  .el-card{
    margin-top: 30px;
    box-shadow: 0 0 5px #ddd;
  }
  .input_box{
    margin: 20px 0;
    .el-input__inner{
      line-height: 46px;
    }
  }
  .el-pagination{
    margin-top: 20px;
  }
  .current_roles_info{
    height: 500px;
    div{
      margin: 20px;
      font-size: 16px;
      span{
        margin-right: 20px;
      }
    }
    .select_box{
      display: flex;
      div{
        margin: 0;
      }
    }
  }
}

</style>